from __future__ import annotations

from typing import Optional

import openai
from wechaty import (
    MessageType,
    Contact,
    Room,
    Message
)
from wechaty import WechatyPlugin
from wechaty_plugin_contrib.message_controller import message_controller
from wechaty_puppet import get_logger

logger = get_logger(__name__)

openai.api_key = "这是从openai那里拿到的key,申请网址在：https://beta.openai.com/account/api-keys"


async def get_info_from_chatgpt(text) -> str:
    print(text)
    if text.startswith("chatgpt"):
        text.replace("chatgpt", "")
        response = openai.Completion.create(
            model="text-davinci-003",
            prompt=text,
            temperature=0,
            max_tokens=2048,
            top_p=1,
            frequency_penalty=0.2,
            presence_penalty=0,
            request_timeout=40
        )
        # res = "可以加老张公众号：\n老张的运维开发日记\n一起学习研究。\nchatgpt的回复，结果仅供参考\n--------------------------\n"
        res = "chatgpt的回复，结果仅供参考\n--------------------------\n"
        choices = response["choices"]
        for choice in choices:
            res = res + choice.get("text").lstrip("\n")
            res = res + "\t"
        return res
    else:
        return "请@我 并用chatgpt打头"


class HowlaisiChatgptPlugin(WechatyPlugin):

    @message_controller.may_disable_message
    async def on_message(self, msg: Message) -> None:

        """
        listen for message event
        """
        talker: Contact = msg.talker()
        room: Optional[Room] = msg.room()

        if room:
            if await msg.mention_self():
                for m in msg.payload.mention_ids:
                    print("----------------------" + m)
                # del msg.payload.mention_ids[0]
                # 以上注释的这句话，不能删，原因是：如果出现msg.mention_text的错误，可排查此句
                print(msg.text())
                print(await msg.mention_text())
                res = await get_info_from_chatgpt(await msg.mention_text())
                await room.say(res, mention_ids=[talker.contact_id])
        else:
            res = await get_info_from_chatgpt(msg.text())
            await talker.say(res)
